#include<iostream>
#include<vector>

using namespace std;

vector<int> spiralOrder(vector<vector<int>>& matrix) {
    int up = 0, down = matrix.size() - 1, l = 0, r = matrix[0].size() - 1;
    vector<int> res;
    while (true)
    {
        for (int i = l; i <= r; i++)   res.push_back(matrix[up][i]);
        if (++up > down) break;
        for (int j = up; j <= down; j++)   res.push_back(matrix[j][r]);
        if (--r < l) break;
        for (int i = r; i >= l; i--)   res.push_back(matrix[down][i]);
        if (--down < up) break;
        for (int j = down; j >= up; j--)   res.push_back(matrix[j][l]);
        if (++l > r) break;
    }
    return res;
}